package zheng.mockit.plugin.http;

import javafx.concurrent.Worker;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import zheng.mockit.plugin.AbstractClient;
import zheng.mockit.plugin.http.message.MockitHttpRequestMessage;
import zheng.mockit.plugin.http.message.MockitHttpResponseMessage;
import zheng.mockit.plugin.http.utils.HttpParamUtils;

import java.io.IOException;
import java.util.Map;

/**
 * Created by zcz on 16-7-29.
 */
public class MockitHttpClient extends AbstractClient {

    private String method;
    private String url;
    private String charset;

    private HttpClient httpClient = HttpClientBuilder.create().build();

    @Override
    public void startup() {
        super.startup();
        this.method = this.configuration.getString("method");
        this.url = this.configuration.getString("url");
        this.charset = StringUtils.defaultString(this.configuration.getString("charset"), "UTF-8");
    }

    @Override
    public void shutdown() {
        super.shutdown();
    }

    @Override
    protected void doSendMessage(Object message) {
        HttpUriRequest request = null;
        if (StringUtils.equalsIgnoreCase(method, "get")) {
            if (message != null) {
                if (message instanceof String) {
                    request = new HttpGet(url + "?" + message.toString());
                } else if (message instanceof Map) {
                    request = new HttpGet(url + "?" + HttpParamUtils.getParamQuery((Map<String, String>) message));
                } else {

                }
            } else {
                request = new HttpGet(url);
            }
        }
        if (StringUtils.equalsIgnoreCase(method, "post")) {
            request = new HttpPost(url);
        }
        try {
            HttpResponse response = httpClient.execute(request);
            StatusLine statusLine = response.getStatusLine();

            //将客户端接收到的结果发往TestCase用于验证。
            MockitHttpResponseMessage httpResponseMessage = new MockitHttpResponseMessage();
            httpResponseMessage.setStatusCode(statusLine.getStatusCode());
            httpResponseMessage.setContent(EntityUtils.toString(response.getEntity(), charset));
            messageHandler.sendMessage2TC(httpResponseMessage);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
